package com.oromwin.repos.server.request.media;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.common.helper.DBHelper;
import com.oromwin.repos.common.helper.FSHelper;
import com.oromwin.repos.common.helper.IOHelper;
import com.oromwin.repos.data.AbstractReposTable;
import com.oromwin.repos.data.FileTable;
import com.oromwin.repos.data.MediaTable;
import com.oromwin.repos.server.LockObject;
import com.oromwin.repos.server.request.AbstractRequest;
import com.oromwin.repos.server.response.NormalResponse;
import com.oromwin.repos.server.response.Response;

public class DeleteMediaRequest extends AbstractRequest {
    private Log log = Logger.getLog(DeleteMediaRequest.class);
    private String MediaId = null;
    private boolean _force = false;

    @Override
    public void receive(DataInputStream dis, LockObject lockObject) throws ReposException {
        try {
            MediaId = IOHelper.readUTF8(dis);
            _force = dis.readBoolean();
        } catch (IOException e) {
            throw ReposException.create(log, e);
        }
    }

    @Override
    public Response run() throws ReposException {
        NormalResponse res = null;
        try {
            getCurrentReposTables();
            checkSameObjectExists();
            String whereClause = String.format("MediaId = '%s'", MediaId);
            if (_force) {
                List<AbstractReposTable> fileTables = DBHelper.selectTable(FileTable.class, whereClause);
                for (AbstractReposTable reposTable : fileTables) {
                    if (reposTable instanceof FileTable) {
                        _fileTable = (FileTable) reposTable;
                        FSHelper.rm(_fileTable.getFullFilepath());
                    }
                }
                DBHelper.deleteTable(FileTable.class, whereClause);
                FSHelper.rm(_mediaTable.getMediaPath());
                DBHelper.deleteTable(MediaTable.class, whereClause);
            } else {
                Statement stmt = DBHelper.createStatement();
                String updateFile = "UPDATE FILE_FileTable SET FileStatus = 1 WHERE " + whereClause;
                stmt.executeUpdate(updateFile);
                String updateMedia = "UPDATE FILE_MediaTable SET MediaStatus = 1 WHERE " + whereClause;
                stmt.executeUpdate(updateMedia);
//                _mediaTable.setMediaStatus(Boolean.TRUE);
//                DBHelper.updateTable(_mediaTable, whereClause);
            }
            res = new NormalResponse(true, "Succeeded to delete media");
        } catch (ReposException e) {
            res = new NormalResponse(false, e.getMessage());
        } catch (SQLException e) {
            res = new NormalResponse(false, e.getMessage());
        } catch (Exception e) {
            String message = String.format("Unexpected exception, {%s}", e.getMessage());
            throw ReposException.create(log, e, message);
        }
        return res;
    }

    @Override
    public void checkSameObjectExists() throws ReposException {
        File filePath = _mediaTable.getMediaPath();
        if (!FSHelper.ls(filePath)) {
            String message = String.format("Same directory already exist on the server, path {%s}", filePath);
            throw ReposException.create(log, message);
        }
    }

    @Override
    public void getCurrentReposTables() throws ReposException {
        AbstractReposTable reposTable = null;
        String whereClause = String.format("MediaId = '%s' AND MediaStatus = 0", MediaId);
        List<AbstractReposTable> reposTables = DBHelper.selectTable(MediaTable.class, whereClause);
        if (reposTables != null && reposTables.size() == 1) {
            reposTable = reposTables.get(0);
        } else {
            String message = String.format("MediaId does not exists in database, tableSize:whereClause {%d:%s}", reposTables.size(), whereClause);
            throw ReposException.create(log, message); 
        }
        if (reposTable instanceof MediaTable) {
            _mediaTable = (MediaTable) reposTable;
        } else {
            String message = String.format("Illegal media table type, class {%s}", reposTable.getClass().toString());
            throw ReposException.create(log, message);
        }
    }
}
